package org.elec.mac.tag;


import lombok.extern.slf4j.Slf4j;
import org.elec.mac.constants.Constants;
import org.elec.mac.ehcache.CacheConfiguration;
import org.elec.mac.entity.SessionUser;
import org.elec.mac.entity.SysAction;
import org.elec.mac.entity.SysUser;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.ApplicationContext;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Bean on 2017/5/19.
 */
@Slf4j
public class RoleActionTag {

    private static CacheConfiguration cacheConfiguration;

    public static void getInstance() {
        if(ObjectUtils.nullSafeEquals(cacheConfiguration, null)) {
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getWebApplicationContext(attr.getRequest().getSession().getServletContext());
            cacheConfiguration = applicationContext.getBean(CacheConfiguration.class);
        }
    }

    /**
     * 角色功能验证
     * @param actioncode
     * @return
     */
    public static Boolean roleActionCode(Long actioncode) {
        Boolean bool = false;
        if(actioncode != null && actioncode > 0L) {
            getInstance();
            EhCacheCacheManager manager
                    = cacheConfiguration.ehCacheCacheManager(cacheConfiguration.ehCacheManagerFactoryBean());
            ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
            SessionUser sessionUser = (SessionUser) attr.getRequest().getSession().getAttribute(Constants.SESSION_USER_KEY);
            Cache authorityCache = manager.getCache("authorityCache");
            String username = authorityCache.get(sessionUser.getToken(), String.class);
            Cache userCache = manager.getCache("userCache");
            SysUser sysUser = userCache.get(username, SysUser.class);
            Cache roleUserCache = manager.getCache("roleUserCache");
            Long roleId = roleUserCache.get(sysUser.getId(), Long.class);
            if (roleId == null) {
                return bool;
            }
            Cache roleActionCache = manager.getCache("roleActionCache");
            List<SysAction> actionList = roleActionCache.get(roleId, ArrayList.class);
            for (SysAction sysAction : actionList) {
                if (actioncode == sysAction.getActionCode()) {
                    bool = true;
                    break;
                }
            }
        }
        return bool;
    }
}
